<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="informationTitle">
        <el-input
          v-model="queryParams.informationTitle"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="informationType">
        <el-select v-model="queryParams.informationType" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="来源" prop="informationSource">
        <el-input
          v-model="queryParams.informationSource"
          placeholder="请输入来源"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="informationAuthor">
        <el-input
          v-model="queryParams.informationAuthor"
          placeholder="请输入作者"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编辑" prop="informationEditor">
        <el-input
          v-model="queryParams.informationEditor"
          placeholder="请输入编辑"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内容" prop="informationContent">
        <el-input
          v-model="queryParams.informationContent"
          placeholder="请输入内容"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布部门ID" prop="issueDepartmentId">
        <el-input
          v-model="queryParams.issueDepartmentId"
          placeholder="请输入发布部门ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布人ID" prop="issueUserId">
        <el-input
          v-model="queryParams.issueUserId"
          placeholder="请输入发布人ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间" prop="issueTime">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.issueTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择发布时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="接收人ID" prop="receiveUserId">
        <el-input
          v-model="queryParams.receiveUserId"
          placeholder="请输入接收人ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接收部门ID" prop="receiveDepartmentId">
        <el-input
          v-model="queryParams.receiveDepartmentId"
          placeholder="请输入接收部门ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="置顶" prop="istop">
        <el-input
          v-model="queryParams.istop"
          placeholder="请输入置顶"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createName">
        <el-input
          v-model="queryParams.createName"
          placeholder="请输入创建人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新人" prop="updateName">
        <el-input
          v-model="queryParams.updateName"
          placeholder="请输入更新人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remake">
        <el-input
          v-model="queryParams.remake"
          placeholder="请输入备注"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:information:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:information:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:information:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:information:export']"
        >导出</el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table @row-dblclick="rowDetails" v-loading="loading" :data="informationList" @selection-change="handleSelectionChange" :max-height="height">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="70" align="center" fixed="left">
        <template scope="scope"> <span>{{scope.$index + (queryParams.pageNum - 1) * queryParams.pageSize + 1}} </span> </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="informationTitle" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="类型" align="center" prop="informationType" :formatter="typeFormat" />
<!--      <el-table-column label="内容" align="center" prop="informationContent" :show-overflow-tooltip="true" :formatter="contentFormat" />-->
<!--      <el-table-column label="来源" align="center" prop="informationSource" :show-overflow-tooltip="true" />-->
<!--      <el-table-column label="作者" align="center" prop="informationAuthor" :show-overflow-tooltip="true" />-->
<!--      <el-table-column label="编辑" align="center" prop="informationEditor" :show-overflow-tooltip="true" />-->
      <el-table-column label="发布部门" align="center" prop="issueDepartmentName" :show-overflow-tooltip="true" />
      <el-table-column label="发布人" align="center" prop="issueUserName" :show-overflow-tooltip="true" />
      <el-table-column label="发布时间" align="center" prop="issueTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.issueTime }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="接收人" align="center" prop="receiveUserName" :show-overflow-tooltip="true" :formatter="receiveUserFormat" />-->
<!--      <el-table-column label="接收部门" align="center" prop="receiveDepartmentName" :show-overflow-tooltip="true" :formatter="receiveDepartmentFormat" />-->
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="置顶" align="center" prop="istop" >
        <template slot-scope="scope">
          <a class='el-icon-upload2' :style="{color:(scope.row.istop==0?'#959595':'#0098ff')}" style="font-size: 25px" @click="handleTopChange(scope.row)"></a>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="downloadAttachment(scope.row)"
          >下载</el-button>
          <router-link :to="'/information/type/data/' + scope.row.informationId" style="margin: 0 10px 0 10px">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
            >查看</el-button>
          </router-link>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:information:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:information:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改新闻资讯对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="informationTitle">
          <el-input v-model="form.informationTitle" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.informationType" placeholder="请选择类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="来源" prop="informationSource">
          <el-input v-model="form.informationSource" placeholder="请输入来源" />
        </el-form-item>
        <el-form-item label="作者" prop="informationAuthor">
          <el-input v-model="form.informationAuthor" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="编辑" prop="informationEditor">
          <el-input v-model="form.informationEditor" placeholder="请输入编辑" />
        </el-form-item>
        <el-form-item label="内容" prop="informationContent">
          <Editor v-model="form.informationContent" />
        </el-form-item>
        <div style="padding-top:50px">
          <el-form-item label="视频地址">
            <el-upload
              ref="upload"
              :action="upload.url"
              :headers="upload.headers"
              :show-file-list="false"
              :on-success="handleFileSuccess">
              <el-button slot="trigger" size="small" type="primary">上传视频文件</el-button>
              <div slot="tip" class="el-upload__tip">如果内容总需要添加视频，请先通过上传视频获取视频地址，复制后通过文本编辑器插入即可！</div>
            </el-upload>
          </el-form-item>
        </div>
        <el-form-item label="上传附件">
          <el-upload
            ref="upload"
            :action="upload.url"
            :headers="upload.headers"
            multiple
            :file-list="upload.fileList"
            :on-success="annexSuccess"
            :on-remove="annexRemove">
            <el-button slot="trigger" size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="接收人">
          <el-tree
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
          <div slot="tip" class="el-upload__tip">可多选，未指定为对所有人公开</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('0')">发 布</el-button>
        <el-button type="primary" @click="submitForm('3')">提 交</el-button>
        <el-button type="primary" @click="submitForm('1')">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInformation, getInformation, delInformation, addInformation, updateInformation, exportInformation, changeTop, treeselect, getFile } from "@/api/system/information";
import Editor from '@/components/Editor';
import { getToken } from "@/utils/auth";
import JSZip from 'jszip'
import FileSaver from 'file-saver'

export default {
  name: "Information",
  components: {
    Editor
  },
  data() {
    return {
      height: (document.documentElement.clientHeight || document.body.clientHeight)-260,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻资讯表格数据
      informationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 类型数据字典
      typeOptions: [],
      // 接受人员部门列表
      menuOptions: [],

      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        informationTitle: null,
        informationType: null,
        informationSource: null,
        informationAuthor: null,
        informationEditor: null,
        informationContent: null,
        issueDepartmentId: null,
        issueUserId: null,
        issueTime: null,
        receiveUserId: null,
        receiveDepartmentId: null,
        status: null,
        istop: null,
        createName: null,
        updateName: null,
        remake: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        informationTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        informationType: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ],
        informationContent: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
/*        issueDepartmentId: [
          { required: true, message: "发布部门ID不能为空", trigger: "blur" }
        ],
        issueUserId: [
          { required: true, message: "发布人ID不能为空", trigger: "blur" }
        ],*/
      },
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("t_news_information_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("t_news_information_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    /** 查询新闻资讯列表 */
    getList() {
      this.loading = true;
      listInformation(this.queryParams).then(response => {
        this.informationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
        informationId: null,
        informationTitle: null,
        informationType: null,
        informationSource: null,
        informationAuthor: null,
        informationEditor: null,
        informationContent: null,
        issueDepartmentId: null,
        issueUserId: null,
        issueTime: null,
        receiveUserId: null,
        receiveDepartmentId: null,
        status: "0",
        istop: null,
        createName: null,
        updateName: null,
        updateTime: null,
        remake: null,
        fileList: [],
        menuIds: [],
      };
      this.upload.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.informationId)
      this.names = selection.map(item => item.informationTitle)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({name:'informationAdd', params:{ row: '' }});
      /*this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加新闻资讯";*/
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.status == 0){
        this.msgSuccess("已发布的文章不能再进行编辑！");
        return;
      }
      this.$router.push({name:'informationEdit', params:{ row: row  }});
      /*this.reset();
      this.getMenuTreeselect();
      const informationId = row.informationId || this.ids
      getInformation(informationId).then(response => {
        this.form = response.data;
        this.form.informationType = ''+this.form.informationType+'';
        this.open = true;
        this.$nextTick(() => {
          const arr = [];
          if (this.form.receiveUserId != null){
            var userids = this.form.receiveUserId.split(",");
            for (var k=0;k<userids.length;k++){
              arr.push(parseInt(userids[k]));
            }
          }
          this.$refs.menu.setCheckedKeys(userids);//获取已经设置的资源后渲染
        });
        this.$nextTick(() => {
          const arr = [];
          if (row.attachmentName != null){
            var attachmentName = row.attachmentName.split(",");
            var attachmentUrl = row.attachmentUrl.split(",");
            var attachmentPath = row.attachmentPath.split(",");
            for (var k=0;k<attachmentName.length;k++){
              arr.push({
                name:attachmentName[k],
                response:{
                  fileName:attachmentPath[k],
                  url:attachmentUrl[k],
                }
              });
            }
          }
          this.upload.fileList=arr;
          this.form.fileList=arr;
        });
        this.title = "修改新闻资讯";
      });*/
    },
    /** 提交按钮 */
    submitForm(statu) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.informationId != null) {
            this.form.status = statu;
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateInformation(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            this.form.status = statu;
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addInformation(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const informationIds = row.informationId || this.ids;
      const informationTitles = row.informationTitle || this.names;
      this.$confirm('是否确认删除新闻资讯标题为"' + informationTitles + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInformation(informationIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有新闻资讯数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportInformation(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.msgSuccess(response.msg);
      this.$alert(response.url, '视频地址', {
        dangerouslyUseHTMLString: true
      });
    },
    // 附件上传成功处理
    annexSuccess(response, file, fileList) {
      this.form.fileList=fileList
    },
    // 附件上传失败处理
    annexRemove(file, fileList) {
      this.form.fileList=fileList
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      treeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    // 所有人员节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.informationType);
    },
    contentFormat(row){
      return row.informationContent.replace(/<[^>]+>/g, '');
    },
    // 接收人为空判断
    receiveUserFormat(row,colum){
      return row.receiveUserName == null?"所有人":row.receiveUserName;
    },
    // 接收部门为空判断
    receiveDepartmentFormat(row,colum){
      return row.receiveDepartmentName == null?"所有部门":row.receiveDepartmentName;
    },
    handleTopChange(row) {
      var num = 0;
      row.istop==1?num=0:num=1;
      changeTop(row.informationId,num);
      row.istop=num;
      return this.handleQuery();
    },
    //下载
    downloadAttachment(row) {
      if (row.attachmentName != null){
        var attachmentName = row.attachmentName.split(",");
        var attachmentUrl = row.attachmentUrl.split(",");
        const zip = new JSZip();
        const cache = {};
        const promises = [];
        for (var i=0;i<attachmentUrl.length;i++){
          setTimeout((function time(i){
            const promise = getFile(attachmentUrl[i]).then(data => { // 下载文件, 并存成ArrayBuffer对象
              const file_name = attachmentName[i]; // 获取文件名
              zip.file(file_name, data, { binary: true }); // 逐个添加文件
              cache[file_name] = data
            })
            promises.push(promise)
          })(i), 0);
        }
        Promise.all(promises).then(() => {
          zip.generateAsync({type:"blob"}).then(content => { // 生成二进制流
            FileSaver.saveAs(content, "附件.zip") // 利用file-saver保存文件
          })
        })
      }else {
        this.msgSuccess("无附件可下载！")
      }
    },
    //双击查看
    rowDetails(row, column, event){
      this.$router.push({name:'InformationDetails', params:{ informationId: row.informationId  }});
    },
  }
};
</script>
